angular.module('Storage', []).factory('storage', function ($rootScope) {

    var storage;

    if (chrome.extension) {
        storage = chrome.extension.getBackgroundPage().backend.storage;
    } else if (localStorage['DownloadHelper']) {
        storage = JSON.parse(localStorage['DownloadHelper']);
    } else {
        storage = {};
    }

    if (!storage['lastUpdate']) {
        storage = {
            "targets": [
                {
                    "name": "links",
                    "element": "a",
                    "attribute": "href"
                }
            ],
            "target_option": 0,
            "selectors": [
                {
                    "name": "is equal to",
                    "jquery": "${element}[${attribute}='${pattern}']"
                },
                {
                    "name": "end with",
                    "jquery": "${element}[${attribute}$='${pattern}']"
                },
                {
                    "name": "matches regEx",
                    "jquery": "${element}:regex(${attribute},${pattern})"
                }
            ],
            "selector_option": 1,
            "patterns": [
                ".zip",
                ".png"
            ],
            "pattern": ".zip"
        };
    }

    storage.persist = chrome.extension ? function () {
        storage['lastUpdate'] = new Date();
        chrome.extension.getBackgroundPage().backend.persist(JSON.parse(JSON.stringify(storage)));
    } : function () {
        storage['lastUpdate'] = new Date();
        localStorage['DownloadHelper'] = JSON.stringify(storage);
    };

    storage.clear = chrome.extension ? function () {
        chrome.extension.getBackgroundPage().backend.clear();
    } : function () {
        delete localStorage['DownloadHelper'];
    };

    return storage;
});